package com.tsing.ipcliveserver.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * Web配置类
 *
 * @author TheTsing
 */
@Configuration
public class ApplicationConfig implements CommandLineRunner {

    private final ServerProperties serverProperties;

    private static final Logger log = LoggerFactory.getLogger(ApplicationConfig.class);

    public ApplicationConfig(ServerProperties serverProperties) {
        this.serverProperties = serverProperties;
    }

    @Bean
    public CorsFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.addAllowedOriginPattern("*");
        config.setMaxAge(18000L);
        config.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

    @Override
    public void run(String... args) {
        String url = "http://localhost:" + serverProperties.getPort() + serverProperties.getServlet().getContextPath() + "/index.html";
        log.info("Console: {}", url);
        try {
            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                Runtime.getRuntime().exec("cmd /c start " + url);
            }
        } catch (Exception ignored) {
        }
    }

}
